package com.ghw.neteasemusic.common.processor;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import com.ghw.neteasemusic.modules.singer.domain.Singer;
import com.ghw.neteasemusic.modules.singer.service.SingerService;
import com.ghw.neteasemusic.modules.song.domain.Song;
import com.ghw.neteasemusic.modules.song.service.SongService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件信息录入到数据库处理器
 *
 * @author violet
 * @since 2021/12/9 23:28
 */
@Slf4j
@Component
@AllArgsConstructor
public class FileToDataBaseProcessor {
    private final SongService songService;
    private final SingerService singerService;

    @SneakyThrows
    public void importSongs() {
        final File dir = FileUtil.file("D:\\Games\\BGM");
        final File[] files = dir.listFiles();

        List<Song> songList = new ArrayList<>();
        List<Singer> singerList = new ArrayList<>();

        long songId = 1L;

        if (null != files) {
            for (File f : files) {
                if (f.isFile()) {
                    final String name = f.getName();
                    if (name.endsWith(".mp3") || name.endsWith(".flac")) {
                        final Song song = new Song();
                        String removeSuffix = "";
                        if (name.endsWith(".mp3")) {
                            removeSuffix = name.replace(".mp3", "");
                        } else if (name.endsWith(".flac")) {
                            removeSuffix = name.replace(".flac", "");
                        }
                        if (removeSuffix.contains("-")) {
                            final String realName = f.getName();
                            final String[] split = removeSuffix.split("-");
                            if (split.length >= 2) {
                                song.setName(split[1].trim());

                                song.setLink("http://localhost:8081/" + realName);
                                song.setId(songId);
                                songList.add(song);
                                songId++;

                                final Singer singer = new Singer();
                                final String temp = split[0].trim();
                                if (NumberUtil.isNumber(temp)) {
                                    singer.setName("网络热门歌手");
                                } else {
                                    singer.setName(temp);
                                }
                                singerList.add(singer);
                            }
                        }
                    }
                }
            }
        }
        songService.saveBatch(songList);
//        singerService.saveBatch(singerList);
    }
}
